import axios from 'axios';
import xml2js from 'xml2js';
import errorCode from "@/utils/errorCode";
import {Message, MessageBox, Notification} from "element-ui";
import store from "@/store";
import {isRelogin} from "@/utils/request";
import Cookies from "js-cookie";
import {decrypt} from "@/utils/jsencrypt";
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: process.env.VUE_APP_BASE_API_X3,
  // 超时
  timeout: 10000
})
// 响应拦截器
service.interceptors.response.use(res => {
    // 未设置状态码则默认成功状态
    const code = res.data.code || 200;
    // 获取错误信息
    const msg = errorCode[code] || res.data.msg || errorCode['default']
    // 二进制数据则直接返回
    if (res.request.responseType ===  'blob' || res.request.responseType ===  'arraybuffer') {
      return res.data
    }
    if (code === 401) {
      if (!isRelogin.show) {
        isRelogin.show = true;
        MessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', { confirmButtonText: '重新登录', cancelButtonText: '取消', type: 'warning' }).then(() => {
          isRelogin.show = false;
          store.dispatch('LogOut').then(() => {
            location.href = '/index';
          })
        }).catch(() => {
          isRelogin.show = false;
        });
      }
      return Promise.reject('无效的会话，或者会话已过期，请重新登录。')
    } else if (code === 500) {
      Message({ message: msg, type: 'error' })
      return Promise.reject(new Error(msg))
    } else if (code === 601) {
      Message({ message: msg, type: 'warning' })
      return Promise.reject('error')
    } else if (code !== 200) {
      Notification.error({ title: msg })
      return Promise.reject('error')
    } else {
      return res.data
    }
  },error => {
    console.log('err' + error)
    let { message } = error;
    if (message == "Network Error") {
      message = "后端接口连接异常";
    } else if (message.includes("timeout")) {
      message = "系统接口请求超时";
    } else if (message.includes("Request failed with status code")) {
      message = "系统接口" + message.substr(message.length - 3) + "异常";
    }
    Message({ message: message, type: 'error', duration: 5 * 1000 })
    return Promise.reject(error)
  }
)
// 登录方法
const callContext="<callContext><codeLang>CHI</codeLang><poolAlias>SYDEV</poolAlias><requestConfig>adxwss.optreturn=JSON&adxwss.beautify=true</requestConfig></callContext>"
const url=""
const url2="/KXJDX3Api/x3api"
const parser = new xml2js.Parser();

function auth(){
  const username = Cookies.get("username");
  const password = decrypt(Cookies.get("password"));
  console.log(username,password)
  return btoa(`${username}:${password}`);
}

export function run(publicName,inputXml) {
  var data = "<Envelope><Body><run>"
  data+=callContext
  data+="<publicName>"+publicName+"</publicName>"
  data+="<inputXml>"+inputXml+"</inputXml>"
  data+="</run></Body></Envelope>"
  var data2={}
  // 将用户名和密码转换为 base64 格式
  const authHeader = auth();
  return new Promise((resolve, reject) => {
    service({
      url: url,
      headers: {
        Authorization: `Basic ${authHeader}`,
        "SOAPAction": "''",
        "Content-Type": "application/xml",
      },
      method: 'post',
      data: data,
    }).then(res => {
      // console.log('x3request.ok',res)
      //解析xml
      parser.parseStringPromise(res).then(res2 => {
        // console.log('x3request.ok2',res2)
        var runReturn = res2["soapenv:Envelope"]["soapenv:Body"][0]["wss:runResponse"][0]["runReturn"][0]
        var status = runReturn.status[0]["_"]
        if(status==1){//成功
          var resultXml = runReturn.resultXml[0]["_"]
          // console.log('x3request.ok3',resultXml)
          resolve(resultXml)
        }
        if(status==0){//失败
          var message = runReturn.messages[0].message[0]
          console.log('x3request.error3',message)
          reject(message)
        }

      }).catch(error2 => {
        console.log('x3request.error2',error2)
      });

    }).catch(error => {
      console.log('x3request.error',error)
      reject(error)
    })
  })
}

export function query(publicName,objectKeys,listSize) {
  var data = "<Envelope><Body><query>"
  data+=callContext
  data+="<publicName>"+publicName+"</publicName>"
  data+="<objectKeys>"+objectKeys+"</objectKeys>"
  data+="<listSize>"+listSize+"</listSize>"
  data+="</query></Body></Envelope>"
  // 将用户名和密码转换为 base64 格式
  const authHeader = auth();
  return new Promise((resolve, reject) => {
    service({
      url: url,
      headers: {
        Authorization: `Basic ${authHeader}`,
        "SOAPAction": "''",
        "Content-Type": "application/xml",
      },
      method: 'post',
      data: data,
    }).then(res => {
      // console.log('x3request.ok',res)
      //解析xml
      parser.parseStringPromise(res).then(res2 => {
        // console.log('x3request.ok2',res2)
        var runReturn = res2["soapenv:Envelope"]["soapenv:Body"][0]["wss:queryResponse"][0]["queryReturn"][0]
        // console.log('x3request.ok2.runReturn',runReturn)
        var status = runReturn.status[0]["_"]
        if(status==1){//成功
          var resultXml = runReturn.resultXml[0]["_"]
          // console.log('x3request.ok3',resultXml)
          resolve({rows:JSON.parse(resultXml),total:JSON.parse(resultXml).length})
        }
        if(status==0){//失败
          var message = runReturn.messages[0].message[0]
          console.log('x3request.error3',message)
          reject(message)
        }

      }).catch(error2 => {
        console.log('x3request.error2',error2)
      });

    }).catch(error => {
      console.log('x3request.error',error)
      reject(error)
    })
  })
}

export function read(publicName,objectKeys) {
  var data = "<Envelope><Body><read>"
  data+=callContext
  data+="<publicName>"+publicName+"</publicName>"
  data+="<objectKeys>"+objectKeys+"</objectKeys>"
  data+="</read></Body></Envelope>"
  // 将用户名和密码转换为 base64 格式
  const authHeader = auth();
  return new Promise((resolve, reject) => {
    service({
      url: url,
      headers: {
        Authorization: `Basic ${authHeader}`,
        "SOAPAction": "''",
        "Content-Type": "application/xml",
      },
      method: 'post',
      data: data,
    }).then(res => {
      // console.log('x3request.ok',res)
      //解析xml
      parser.parseStringPromise(res).then(res2 => {
        // console.log('x3request.ok2',res2)
        var runReturn = res2["soapenv:Envelope"]["soapenv:Body"][0]["wss:readResponse"][0]["readReturn"][0]
        // console.log('x3request.ok2.runReturn',runReturn)
        var status = runReturn.status[0]["_"]
        if(status==1){//成功
          var resultXml = runReturn.resultXml[0]["_"]
          // console.log('x3request.ok3',resultXml)
          resolve({data:JSON.parse(resultXml)})
        }
        if(status==0){//失败
          var message = runReturn.messages[0].message[0]
          console.log('x3request.error3',message)
          reject(message)
        }

      }).catch(error2 => {
        console.log('x3request.error2',error2)
      });

    }).catch(error => {
      console.log('x3request.error',error)
      reject(error)
    })
  })
}

export function modify(publicName,objectKeys,objectXml) {
  var data = "<Envelope><Body><modify>"
  data+=callContext
  data+="<publicName>"+publicName+"</publicName>"
  data+="<objectKeys>"+objectKeys+"</objectKeys>"
  data+="<objectXml>"+JSON.stringify(objectXml)+"</objectXml>"
  data+="</modify></Body></Envelope>"
  // console.log(objectXml)
  // 将用户名和密码转换为 base64 格式
  const authHeader = auth();
  return new Promise((resolve, reject) => {
    service({
      url: url,
      headers: {
        Authorization: `Basic ${authHeader}`,
        "SOAPAction": "''",
        "Content-Type": "application/xml",
      },
      method: 'post',
      data: data,
    }).then(res => {
      // console.log('x3request.ok',res)
      //解析xml
      parser.parseStringPromise(res).then(res2 => {
        // console.log('x3request.ok2',res2)
        var runReturn = res2["soapenv:Envelope"]["soapenv:Body"][0]["wss:modifyResponse"][0]["modifyReturn"][0]
        // console.log('x3request.ok2.runReturn',runReturn)
        var status = runReturn.status[0]["_"]
        if(status==1){//成功
          // var resultXml = runReturn.resultXml[0]["_"]
          // console.log('x3request.ok3',resultXml)
          resolve()
        }
        if(status==0){//失败
          var message = runReturn.messages[0].message[0]
          console.log('x3request.error3',message)
          reject(message)
        }

      }).catch(error2 => {
        console.log('x3request.error2',error2)
      });

    }).catch(error => {
      console.log('x3request.error',error)
      reject(error)
    })
  })
}

export function save(publicName,objectXml) {
  var data = "<Envelope><Body><save>"
  data+=callContext
  data+="<publicName>"+publicName+"</publicName>"
  data+="<objectXml>"+JSON.stringify(objectXml)+"</objectXml>"
  data+="</save></Body></Envelope>"
  // console.log(objectXml)
  // 将用户名和密码转换为 base64 格式
  const authHeader = auth();
  return new Promise((resolve, reject) => {
    service({
      url: url,
      headers: {
        Authorization: `Basic ${authHeader}`,
        "SOAPAction": "''",
        "Content-Type": "application/xml",
      },
      method: 'post',
      data: data,
    }).then(res => {
      // console.log('x3request.ok',res)
      //解析xml
      parser.parseStringPromise(res).then(res2 => {
        // console.log('x3request.ok2',res2)
        var runReturn = res2["soapenv:Envelope"]["soapenv:Body"][0]["wss:saveResponse"][0]["saveReturn"][0]
        // console.log('x3request.ok2.runReturn',runReturn)
        var status = runReturn.status[0]["_"]
        if(status==1){//成功
          // var resultXml = runReturn.resultXml[0]["_"]
          // console.log('x3request.ok3',resultXml)
          resolve()
        }
        if(status==0){//失败
          var message = runReturn.messages[0].message[0]
          console.log('x3request.error3',message)
          Message({ message: message, type: 'error', duration: 5 * 1000 })
          reject(message)
        }

      }).catch(error2 => {
        console.log('x3request.error2',error2)
        Message({ message: error2, type: 'error', duration: 5 * 1000 })
      });

    }).catch(error => {
      console.log('x3request.error',error)
      Message({ message: error, type: 'error', duration: 5 * 1000 })
      reject(error)
    })
  })
}

export function del(publicName,objectKeys) {
  var data = "<Envelope><Body><delete>"
  data+=callContext
  data+="<publicName>"+publicName+"</publicName>"
  data+="<objectKeys>"+objectKeys+"</objectKeys>"
  data+="</delete></Body></Envelope>"
  // console.log(objectXml)
  // 将用户名和密码转换为 base64 格式
  const authHeader = auth();
  return new Promise((resolve, reject) => {
    service({
      url: url,
      headers: {
        Authorization: `Basic ${authHeader}`,
        "SOAPAction": "''",
        "Content-Type": "application/xml",
      },
      method: 'post',
      data: data,
    }).then(res => {
      // console.log('x3request.ok',res)
      //解析xml
      parser.parseStringPromise(res).then(res2 => {
        // console.log('x3request.ok2',res2)
        var runReturn = res2["soapenv:Envelope"]["soapenv:Body"][0]["wss:deleteResponse"][0]["deleteReturn"][0]
        // console.log('x3request.ok2.runReturn',runReturn)
        var status = runReturn.status[0]["_"]
        if(status==1){//成功
          // var resultXml = runReturn.resultXml[0]["_"]
          // console.log('x3request.ok3',resultXml)
          resolve()
        }
        if(status==0){//失败
          var message = runReturn.messages[0].message[0]
          console.log('x3request.error3',message)
          reject(message)
        }

      }).catch(error2 => {
        console.log('x3request.error2',error2)
      });

    }).catch(error => {
      console.log('x3request.error',error)
      reject(error)
    })
  })
}

export function actionObject(publicName,objectXml,actionCode) {
  var data = "<Envelope><Body><actionObject>"
  data+=callContext
  data+="<publicName>"+publicName+"</publicName>"
  data+="<objectXml>"+JSON.stringify(objectXml)+"</objectXml>"
  data+="<actionCode>"+actionCode+"</actionCode>"
  data+="</actionObject></Body></Envelope>"
  // console.log(objectXml)
  // 将用户名和密码转换为 base64 格式
  const authHeader = auth();
  return new Promise((resolve, reject) => {
    service({
      url: url,
      headers: {
        Authorization: `Basic ${authHeader}`,
        "SOAPAction": "''",
        "Content-Type": "application/xml",
      },
      method: 'post',
      data: data,
    }).then(res => {
      // console.log('x3request.ok',res)
      //解析xml
      parser.parseStringPromise(res).then(res2 => {
        // console.log('x3request.ok2',res2)
        var runReturn = res2["soapenv:Envelope"]["soapenv:Body"][0]["wss:actionObjectResponse"][0]["actionObjectReturn"][0]
        // console.log('x3request.ok2.runReturn',runReturn)
        var status = runReturn.status[0]["_"]
        if(status==1){//成功
          // var resultXml = runReturn.resultXml[0]["_"]
          // console.log('x3request.ok3',resultXml)
          resolve()
        }
        if(status==0){//失败
          var message = runReturn.messages[0].message[0]
          console.log('x3request.error3',message)
          reject(message)
        }

      }).catch(error2 => {
        console.log('x3request.error2',error2)
      });

    }).catch(error => {
      console.log('x3request.error',error)
      reject(error)
    })
  })
}
